package cn.woowc.through.listener;

import cn.woowc.through.listener.event.ThroughApplicationEvent;
import cn.woowc.through.listener.event.ThroughDingUrlInfo;
import cn.woowc.through.listener.event.ThroughNatLogInfo;
import cn.woowc.through.thread.BatThreadFactory;
import cn.woowc.through.thread.NotifyUrlRunnable;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.ApplicationListener;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * @version V1.0.0
 * @ClassName: {@link ThroughApplicationEvent}
 * @Description: ThroughApplicationListener
 * @author: Lanzhou
 * @date: 2021/3/11 16:47
 * @Copyright:2020 All rights reserved.
 */
@Slf4j
public class ThroughApplicationListener implements ApplicationListener<ThroughApplicationEvent> {

    /**
     * 启动后将日志信息返回给当前监听器, 同时发送最新的Socket链接地址
     *
     * @param event 事件名称
     */
    @Override
    public void onApplicationEvent(ThroughApplicationEvent event) {
        Object source = event.getSource();
        String className = null;
        String path = null;
        if (source instanceof ThroughNatLogInfo) {
            ThroughNatLogInfo info = (ThroughNatLogInfo) source;
            path = info.getPath();
            className = info.getClass().getName();
        } else if (source instanceof ThroughDingUrlInfo) {
            ThroughDingUrlInfo info = (ThroughDingUrlInfo) source;
            path = info.getPath();
            className = info.getClass().getName();
        }
        ExecutorService service = new ThreadPoolExecutor(1, 1,
                0L, TimeUnit.MILLISECONDS,
                new LinkedBlockingQueue<>(), new BatThreadFactory());
        //启动两个线程，一个线程负责读标准输出流，另一个负责读标准错误流
        service.submit(new NotifyUrlRunnable(path, className));
        service.shutdown();
    }

}
